package cn.com.w.web.Handler;

import cn.com.w.common.PublicHandler.PublicHandler;
import cn.com.w.common.param.BlogParam;
import cn.com.w.dao.Entity.TBlog;
import cn.com.w.dao.Entity.TBlogTags;
import cn.com.w.dao.Service.ITBlogService;
import cn.com.w.dao.Service.ITBlogTagsService;
import cn.com.w.secutity.Security.JwtTokenUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class BlogHandler {

    private final JwtTokenUtils jwtTokenUtils;
    private final ITBlogService blogService;
    private final ITBlogTagsService itBlogTagsService;

    public BlogHandler(JwtTokenUtils jwtTokenUtils, ITBlogService blogService, ITBlogTagsService itBlogTagsService) {
        this.jwtTokenUtils = jwtTokenUtils;
        this.blogService = blogService;
        this.itBlogTagsService = itBlogTagsService;
    }

    public String getStringByTagIds(List<Long> tagIds) {
        StringBuilder tagIdsString = new StringBuilder();
        for (Long tagId : tagIds) {
            tagIdsString.append(tagId).append(",");
        }
        return tagIdsString.toString();
    }


    public boolean saveBlog(BlogParam param, String token) {
        List<TBlogTags> blogTags = new ArrayList<>();
        Long userId = jwtTokenUtils.getUserIdFromToken(token);
        TBlog blog = TBlog.builder()
                .appreciation(param.isAppreciation())
                .content(param.getContent())
                .flag(param.getFlag())
                .firstPicture(param.getFirstPicture())
                .published(param.isPublished())
                .recommend(param.isRecommend())
                .shareStatement(param.isShareStatement())
                .title(param.getTitle())
                .views(param.getViews())
                .commentabled(param.isCommentabled())
                .createTime(LocalDateTime.now())
                .description(param.getDescription())
                .shareStatement(param.isShareStatement())
                .typeId(param.getType())
                .updateTime(LocalDateTime.now())
                .userId(userId)
                .build();
        for (Long tagsId : param.getTags()) {
            blogTags.add(TBlogTags.builder()
                    .blogsId(blog.getId())
                    .tagsId(tagsId)
                    .build());
        }
        return PublicHandler.saveOne(blog, blogService) && PublicHandler.saveAll(blogTags, itBlogTagsService);
    }


}
